import { View } from '@tarojs/components'
import Taro, { usePullDownRefresh,useReachBottom,stopPullDownRefresh } from '@tarojs/taro'
import { useEffect, useState } from 'react'
import './index.scss'

//定义类型
interface Item {
  title: string,
  body: string
}

interface Param {
  current: 1,
  pageSize: 10
}

function getList(params: Param) {
  const {current, pageSize} = params
  return new Promise((resolve) => {
    //请求接口方法
    Taro.request({
      url: 'http://jsonplaceholder.typicode.com/posts',
      //接口请求成功就会执行下面的函数
      success: (res) => {
        let output = res.data.splice((current - 1) * pageSize, pageSize)
        resolve(output)
      }
    })
  })
}

function RequestList() {
  const [list, setList] = useState<Item[]>([])
  const [loading, setLoading] = useState(true)
  const [num,setNum] = useState(2)
  const [page, setPage] = useState(20)
  const [lastPage, setLastPage] = useState(false)

  //下拉刷新
  usePullDownRefresh(() => {
    //Promise方法
    getList({ current: 1, pageSize: page }).then(res => {
      setList(res as any)
      setLoading(false)
      setNum(2)
      setLastPage(false)
      stopPullDownRefresh()
    })
  })

  // 小于 10 页
  // 小于 10 条数据
  //上拉刷新
  useReachBottom(() => {
    if (lastPage) return
    getList({ current: num , pageSize: page }).then(res => {
      if (res.length === page){
        let arr = list.concat(res)
        setList(arr as any)
        setNum(num + 1)
      } else if (res.length < page){
        let arr = list.concat(res)
        setList(arr as any)
        setLastPage(true)
      }
    })
  })


  // 在组件渲染完成之后执行这个函数
  // 在约定的状态变化导致组件重新执行 1次
  //这里约定的状态是数组[]变化
  useEffect(() => {
    getList({ current: 1, pageSize: page }).then(res => {
      setList(res as any)
      setLoading(false)
    })
  }, [])

  // 上拉加载
  // 拉倒底加载一页到页面中，一页十条数据
  //拉倒第十页没有数据了，显示一个提示已经到底了


  if (loading) {
    return (
      <View className='index'>
        <View>数据加载中...</View>
      </View>
    )
  }

  return (
    <View className='cards'>
      {
        list.map((itme) => (
          <View className='card'>
            <View className='card-img'></View>
            <View className='card-title'>{itme.title}</View>
            <View className='card-text'>{itme.body}</View>
          </View>
        ))
      }
      <View className={lastPage ? 'hint' : 'hint-none'}>没有更多了</View>
    </View>
  )
}

export default RequestList